import { defineStore } from 'pinia'

type CoinResult = number[] // [第一次,第二次,第三次] 例如[2,2,3]

export const useProgressStore = defineStore('progress', {
  state: () => ({
    // 当前进度状态
    currentStep: 0, // 0=未开始 1-6=进行中 7=完成
    question: '',
    coinsHistory: [] as CoinResult[],
    finalHexagram: '',
    
    // 时间戳用于判断是否过期
    lastUpdated: 0 
  }),
  
  actions: {
    // 保存当前进度
    saveProgress(payload: Partial<this['$state']>) {
      this.$patch({
        ...payload,
        lastUpdated: Date.now()
      })
      this.persist()
    },
    
    // 持久化到localStorage
    persist() {
      localStorage.setItem(
        'divinationProgress', 
        JSON.stringify(this.$state)
      )
    },
    
    // 从存储恢复
    restore() {
      const saved = localStorage.getItem('divinationProgress')
      if (saved) {
        const parsed = JSON.parse(saved)
        // 超过1小时的进度视为过期
        if (Date.now() - parsed.lastUpdated < 3600000) {
          this.$patch(parsed)
          return true
        }
        this.clear()
      }
      return false
    },
    
    // 清除进度
    clear() {
      this.$reset()
      localStorage.removeItem('divinationProgress')
    }
  }
})